package aliyun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;

public class AliYunUpload {
	private static final String ACCESS_ID = "Z41pj432QlmWYY3u";
	public static final String ACCESS_KEY = "U9OkzIU1jiMLHEsnhIgXR99kSCE7Zb";
	public static final String OSS_ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";
	private static final String BUCKET_NAME = "naer-app";

/**
 * 
 * 
 * @param key   阿里云的文件名
 * @param filename   本地文件的绝对路径
 * @throws OSSException
 * @throws ClientException
 * @throws FileNotFoundException
 */
	public static void uploadFile(String key, String filename,String contentType)
			throws OSSException, ClientException, FileNotFoundException {
		File file = new File(filename);
		InputStream input = new FileInputStream(file);
		long contentLength=file.length();
		uploadFile(key, input,contentLength,contentType);
	}
	/**
	 * 
	 * @param key
	 * @param input
	 * @param contentLength
	 * @throws OSSException
	 * @throws ClientException
	 * @throws FileNotFoundException
	 */
	public static void uploadFile(String key, InputStream input,long contentLength,String contentType)
			throws OSSException, ClientException, FileNotFoundException {
		ClientConfiguration config = new ClientConfiguration();
		OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY, config);
		ensureBucket(client, BUCKET_NAME);
		try {
			setBucketPublicReadable(client, BUCKET_NAME);
		} catch(Exception e){
			System.exit(0);				
		}
		ObjectMetadata objectMeta = new ObjectMetadata();
		objectMeta.setContentLength(contentLength);
//		objectMeta.setContentType("image/jpeg");	
		objectMeta.setContentType(contentType);
		client.putObject(BUCKET_NAME, key, input, objectMeta);
	}


	// 创建Bucket.
	private  static void ensureBucket(OSSClient client, String bucketName) throws OSSException, ClientException {
		try {
			// 创建bucket
			client.createBucket(bucketName);
		} catch (ServiceException e) {
			if (!OSSErrorCode.BUCKET_ALREADY_EXISTS.equals(e.getErrorCode())) {
				// 如果Bucket已经存在，则忽略
				throw e;
			}
		}
	}

	// 把Bucket设置为所有人可读
	private static void setBucketPublicReadable(OSSClient client, String bucketName)
			throws OSSException, ClientException {
		// 创建bucket
		client.createBucket(bucketName);
		// 设置bucket的访问权限，public-read-write权限
		client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
	}
}
